﻿Ext.define("GS.controller.User", {
    extend: "Ext.app.Controller",

    config: {
        refs: {
            registerView: "userregister",
            loginView: "userlogin",
            mainView: "main",
            editProfileView: "editprofile",
            profileView: "profileview",
            btnRegisterView: "#btnRegisterView",
            btnLoginView: "#btnLoginView",
            btnLogin: "#btnLogin",
            btnRegister: "#btnRegister",
            btnLogout: "#btnLogout",
            btnEditProfile: "#btnEditProfile",
            btnCancelEditProfile: "#btnCancelEditProfile",
            btnUpdateProfile: "#btnUpdateProfile"
            //RegisterForm: '#registerform'
        },
        control: {
            btnRegisterView: {
                tap: "onRegisterView"
            },
            btnLoginView: {
                tap: "onLoginView"
            },
            btnLogin: {
                tap: "onLogin"
            },
            btnRegister: {
                tap: "onRegister"
            },
            btnLogout: {
                tap: "onLogout"
            },
            btnEditProfile: {
                tap: "onEditProfile"
            },
            btnCancelEditProfile: {
                tap: "onCancelEditProfile"
            },
            btnUpdateProfile: {
                tap: "onUpdateProfile"
            }
        }
    },
    onRegisterView: function () {
        Ext.Viewport.setActiveItem(this.getRegisterView());
    },
    onLoginView: function () {
        Ext.Viewport.setActiveItem(this.getLoginView());
    },
    onEditProfile: function (id) {
        Ext.Viewport.setActiveItem(this.getEditProfileView());
    },
    onCancelEditProfile: function (id) {
        Ext.Viewport.setActiveItem(this.getMainView());
    },
    onLogout: function (id) {
        var user = Ext.create('GS.store.UserData');

        user.load();

        user.removeAll();

        user.sync();

        Ext.Viewport.setActiveItem(this.getLoginView());
    },
    doLogin: function (response) {
        var user = Ext.create('GS.model.user.User', { user_id: response.id, email: response.email, first_name: response.first_name, last_name: response.last_name, school_id: response.school_id, logged_in: true });
        user.save();
        Ext.Viewport.setActiveItem(this.getMainView());
    },
    onLogin: function () {
        var values = this.getLoginView().getValues();
        var doLoginContainer = this;

        if (values.email != "" && values.password != "") {
            Ext.data.JsonP.request({
                url: GS.util.Config.getServerUrl()+'Login.php',
                callbackKey: "callback",
                params: { email: values.email, password: values.password },

                success: function (response) {
                    var text = response.responseText;
                    if (response.success == "true") {
                        Ext.Msg.alert('Velkommen', 'Du er nu logget ind');
                        doLoginContainer.doLogin(response);
                    }
                    else {
                        Ext.Msg.alert('Fejl', 'Email eller password forkert!');
                    }
                },

                failure: function (response) {
                    Ext.Msg.alert('Fejl!', 'Der kunne ikke oprettes forbindelse til serveren.');
                    //console.log(response.responseText);
                }
            });
        }
        else {
            Ext.Msg.alert('Fejl!', 'Udfyld email og kodeord.');
        }
    },
    onRegister: function () {
        var values = this.getRegisterView().getValues();
        var doLoginContainer = this;

        var model = Ext.create('GS.model.user.User', values);

        var errors = model.validate();

        if(errors.isValid()){
            Ext.data.JsonP.request({
                url: GS.util.Config.getServerUrl()+'Register.php',
                callbackKey: "callback",
                params: { email: values.email, password: values.password, first_name: values.first_name, last_name: values.last_name, school_id: values.school },

                success: function (response) {
                    var text = response.responseText;
                    Ext.Msg.alert('Din bruger er registreret', text);
                    doLoginContainer.doLogin(response);
                },

                failure: function (response) {
                    Ext.Msg.alert('Fejl!', 'Der kunne ikke oprettes forbindelse til serveren.');
                    //console.log(response.responseText);
                }
            });
        } else {
            var errorMessage = "";
            Ext.each(errors.items, function (rec, i) {
                errorMessage += rec.config.message + "<br/>";
            });
            Ext.Msg.alert("Fejl", errorMessage, function () { });
            return false;
        }
    },
    onUpdateProfile: function () {
        var values = this.getEditProfileView().getValues();

        var doLoginContainer = this;

        var user = Ext.create('GS.store.UserData');

        user.load();

        var user_id = user.getAt(0).get('user_id');

        var model = Ext.create('GS.model.user.User', values);

        var errors = model.validate();

        if(errors.isValid()){
            Ext.data.JsonP.request({
                url: GS.util.Config.getServerUrl()+'UpdateUser.php',
                callbackKey: "callback",
                params: { user_id: user_id, email: values.email, password: values.password, first_name: values.first_name, last_name: values.last_name, school_id: values.school },

                success: function (response) {
                    var text = response.responseText;
                    Ext.Msg.alert('Bruger', 'Din bruger er opdateret');

                    var user = Ext.create('GS.store.UserData');
                    user.load();
                    user.removeAll();
                    user.sync();

                    doLoginContainer.doLogin(response);
                    doLoginContainer.getProfileView().fireEvent('show');
                },

                failure: function (response) {
                    Ext.Msg.alert('Fejl!', 'Der kunne ikke oprettes forbindelse til serveren.');
                    //console.log(response.responseText);
                }
            });
        } else {
            var errorMessage = "";
            Ext.each(errors.items, function (rec, i) {
                errorMessage += rec.config.message + "<br/>";
            });
            Ext.Msg.alert("Fejl", errorMessage, function () { });
            return false;
        }
    }
});